﻿/**
* CRL
*/
using CRL.RedisProvider;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using CRL.Core.Extension;
using System.Threading.Tasks;

namespace CRL.EventBus.Queue
{
    class Redis : AbsQueue
    {
        StackExchangeRedisHelper client;
        ConfigBase _queueConfig;
        public override MQType MQType => MQType.Redis;
        public Redis(ConfigBase queueConfig)
        {
            client = new StackExchangeRedisHelper("");
            _queueConfig = queueConfig;
        }
        public override void Dispose()
        {
     
        }
        public override void PublishList(string routingKey, IEnumerable<object> msgs, Action<PublishOption> optFunc = null)
        {
            var opt = new PublishOption();
            optFunc?.Invoke(opt);
            var data = new MsgPackage { _InnerData = msgs.ToJson(), RoutingKey = routingKey, MsgKey = opt.MsgKey };
            client.Publish(routingKey, data.ToJson());
        }
        public override Task PublishListAsync(string routingKey, IEnumerable<object> msgs, Action<PublishOption> optFunc = null)
        {
            var opt = new PublishOption();
            optFunc?.Invoke(opt);
            var data = new MsgPackage { _InnerData = msgs.ToJson(), RoutingKey = routingKey, MsgKey = opt.MsgKey };
            return client.PublishAsync(routingKey, data.ToJson());
        }
        public override void RePublish(IData data, object msg)
        {
            var data2 = new MsgPackage
            {
                _InnerData = msg.ToJson(),
                RoutingKey = data.RoutingKey,
                RetryTimes = data.RetryTimes + 1,
                Priority = data.Priority,
                MsgKey = data.MsgKey,
                Time = data.Time
            };
            client.Publish(data.RoutingKey, data2.ToJson());
        }

        public override void Subscribe(EventDeclare eventDeclare)
        {
            var routingKey = eventDeclare.Name;
            client.Subscribe(routingKey, OnReceiveString);
        }

        public override void SubscribeAsync(EventDeclare eventDeclare)
        {
            var routingKey = eventDeclare.Name;
            var task = client.SubscribeAsync(routingKey, OnReceiveString);
            task.Wait();
        }
    }

//    class RedisPublisher : AbsPublisher
//    {
//#if NETSTANDARD 
//        public RedisPublisher(Microsoft.Extensions.Options.IOptions<QueueConfig> options) : base(options.Value)
//        {
//            queue = QueueFactory.CreateClient(options.Value.GetMqSetting(MQType.Redis), false);
//            //queueConfig = options.Value;
//        }
//#endif
//        public RedisPublisher(QueueConfig _queueConfig) : base(_queueConfig)
//        {
//            queue = QueueFactory.CreateClient(_queueConfig.GetMqSetting(MQType.Redis), false);
//        }
//    }
}
